#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Wed Jan  9 10:12:16 2019

@author: DELL
"""
import matplotlib
matplotlib.use("Agg")
import data1_label
import matplotlib.pyplot as plt
import keras
from keras.layers import Dense,Dropout,Conv1D,Flatten,LSTM,Input
from keras.models import Model
from keras.callbacks import EarlyStopping
import os
import datetime

os.environ["CUDA_VISIBLE_DEVICES"] = "7"
timestep=31

def subtime(date1,date2):
    date1=datetime.datetime.strptime(date1,"%Y-%m-%d %H:%M:%S")
    date2=datetime.datetime.strptime(date2,"%Y-%m-%d %H:%M:%S")
    return date2-date1

cwd=os.getcwd()
def txt_create(name,msg):
    fullpath=cwd+'/'+name+'.txt'
    file=open(fullpath,'w')
    file.write(msg)
    file.close()


train_x=data1_label.x_train
train_y=data1_label.y_train

input=Input(shape=(timestep,24))
#print(input.shape)
r_layer1=LSTM(70,activation='relu',return_sequences=True)(input)
#r_layer2=LSTM(150,activation='relu',return_sequences=True)(r_layer1)
r_layer2=Dropout(0.9)(r_layer1)
r_layer2=Flatten()(r_layer2)

c_layer1=Conv1D(70,31,activation='relu',padding='same')(input)
#c_layer1=keras.layers.BatchNormalization()(c_layer1)

c_layer2=Conv1D(70,31,activation='relu',padding='same')(c_layer1)
#c_layer2=keras.layers.BatchNormalization()(c_layer2)
c_layer2=Flatten()(c_layer2)
#c_pool=GlobalAveragePooling1D()(c_layer2)

merge=keras.layers.concatenate([r_layer2,c_layer2])
output=Dense(1,activation='relu')(merge)
model=Model(inputs=[input],outputs=output)
model.compile(loss='mse',optimizer='adam',metrics=['accuracy'])

startdate=datetime.datetime.now()
startdate=startdate.strftime("%Y-%m-%d %H:%M:%S")

model.save('./fcn1.h5')
early_stopping=EarlyStopping(monitor='val_loss',patience=20,verbose=1,mode='min')
history=model.fit(train_x,train_y,epochs=800,batch_size=128,validation_data=(data1_label.x_validate,data1_label.y_validate),callbacks=[early_stopping],verbose=1)

enddate=datetime.datetime.now()
enddate=enddate.strftime("%Y-%m-%d %H:%M:%S")

print('start date',startdate)
print('end date',enddate)
print('time',subtime(startdate,enddate))

loss=history.history['loss']
val_loss=history.history['val_loss']

plt.plot(loss,label='train loss')
plt.plot(val_loss,label='validate loss')
plt.legend()
plt.savefig('loss_fcnlstm1.jpg')

loss=','.join([str(x) for x in loss])
val_loss='\n'.join([str(x) for x in val_loss])

txt_create('loss_fcnlstm1',loss)
txt_create('val_loss_fcnlstm1',val_loss)


